import loginApi from '../../api/login'
import userApi from '../../api/userInfo'
import storage from '../../utils/storage'
import { toast } from '../../utils/util'
const app = getApp()
Page({
  data: {
    statusBarHeight: wx.getSystemInfoSync()['statusBarHeight'],
    count: 60,
    isShow: false,
    wxCode: '',
    from: {
      phone: '',
      verify: '',
    },
    flag: false
  },
  onLoad(options) {},
  change(e) {
    let type = e.currentTarget.dataset.type
    this.data.from[type] = e.detail.value
    this.setData({
      from: this.data.from
    })
  },
  changeTab() {
    if(this.data.flag){
      this.setData({
        flag: false
      })
    } else {
      this.setData({
        flag: true
      })
    }
  },
  linkTo() {
    wx.navigateBack()
  },

  getPhoneNumber (e) {
    if(e.detail.errMsg === 'getPhoneNumber:ok') {
      this.login(e.detail.code);
    }
  },
  sendCode () {
    let that = this
    let params = {
      phonenumber: `${that.data.from?.phone}`,
      scene: '1'
    }
    loginApi.sendSmsCode(params).then(res => {
      let timer = setInterval(() => {
        if(that.data.count > 0){
          that.data.count--
          that.setData({
            count: that.data.count,
            isShow: true
          })
        } else {
          clearInterval(timer)
          that.setData({
            count: 60,
            isShow: false
          })
        }
      }, 1000);
    })
  },
  //登录
  login(code) {
    wx.login({
      success: res => {
        console.log(res.code)
        if (res.code) {
          let params = {
            phoneCode: code,
            loginCode: res.code,
            state: app.globalData.clientId
          }
          loginApi.login(params).then(res => {
            if (res.data.bindingFlag) {
              storage.set('token',res.data.access_token);
              this.linkTo();
            }
          })
        }
      }
    })
  },
  // 手机号登录
  phoneLogin () {
    let params = {
      mobile: this.data.from.phone,
      code: this.data.from.verify,
      state: app.globalData.clientId
    }
    loginApi.smsLogin(params).then(res => {
        storage.set('token',res.data.access_token);
        this.linkTo();
    })
  },
  // 用户信息
  getUserInfo () {
    userApi.getUserInfo().then(res => {
      storage.set('userInfo', res.data);
      this.linkTo();
    })
  },
})